import fs from 'fs'; 
import path from 'path';
import Show from "./show.js";
import data from './XdxzData.js';
import puppeteer from "../../../lib/puppeteer/puppeteer.js";

export const PLUGIN_PATH = path.join(path.resolve(), 'plugins', 'xdxz');
const FILE_PATH = {
    player: path.join(PLUGIN_PATH, 'data', 'player')
};
/** 创建群文件夹 */
export function createAGroupFolder(GROUP_ID) {
    fs.mkdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString()), { recursive: true })
    fs.mkdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'beibao'),{ recursive: true })
    fs.mkdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'work'),{ recursive: true })
}
/** 判断群是否存在 */
export function isGroupExist(GROUP_ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString().toString()))) {
        return true
    }
    return false
}
/** 判断玩家是否存在 */
export function isPlayerExist(GROUP_ID, ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'))) {
        return true
    }
    return false
}
/** 存储玩家数据 */
export function storagePlayerData(GROUP_ID, ID, DATA) {
    fs.writeFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'), JSON.stringify(DATA, null, 4));
}
/** 读取玩家数据 */
export async function getPlayerData(GROUP_ID, ID) {
    const DATA = await JSON.parse(fs.readFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'), 'utf8'))
    return DATA
}
/** 读取玩家背包数据 */
export async function getBeibaoData(GROUP_ID, ID) {
    const DATA = await JSON.parse(fs.readFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'beibao', ID + '.json'), 'utf8'))
    return DATA
}
//星币数量正增加,负减少
//使用时记得加await
export async function Add_星币(GROUP_ID, ID, 星币数量 = 0) {
	let player = await getPlayerData(GROUP_ID, ID);
	player.xingbi+= Math.trunc(星币数量);
	await Write_player(GROUP_ID, ID, player);
	return;
}
//写入存档信息,第二个参数是一个JavaScript对象
export async function Write_player(GROUP_ID, ID, player) {
	let dir = path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json');
	let new_ARR = JSON.stringify(player, '', '\t');
	fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
		console.log('写入成功', err);
	});
	return;
}
/** 判断玩家背包文件是否存在 */
export function isbeibao(GROUP_ID, ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'beibao' ,ID + '.json'))) {
        return true
    }
    return false
}
/** 创建玩家背包文件数据 */
export function beibaoData(GROUP_ID, ID, DATA) {
    fs.writeFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'beibao' ,ID + '.json'), JSON.stringify(DATA, null, 2));
}
/** 判断玩家工作文件是否存在 */
export function iswork(GROUP_ID, ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'work' ,ID + '.json'))) {
        return true
    }
    return false
}
/* 删除工作文件*/
export function delework(GROUP_ID, ID){
    if(fs.unlink(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'work' ,ID + '.json'))){
        return true
    }
    return false
}
/** 创建玩家工作文件数据 */
export function workData(GROUP_ID, ID, DATA) {
    fs.writeFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), 'work' ,ID + '.json'), JSON.stringify(DATA, null, 2));
}
/**
 * 增加减少背包物品
 * @param ID[0] 操作存档的qq号
 * @param thing_name  物品名称
 * @param thing_class  物品类别
 * @param n  操作的数量,取+增加,取 -减少
 * @param pinji 品级 数字0-6
 * @returns 无
 */
export async function Add_beibao_thing(GROUP_ID, ID,thing_name,thing_class,n,pinji = null) {
    var x = n;
	if (x == 0) {
		return;
	}
	x = Number(x);
    let beibao = await Read_beibao(GROUP_ID, ID);
    var name = thing_name;
    if (!isNotNull(beibao.饮料)) {
		//判断老存档有没有饮料字段
		beibao.饮料 = [];
	}
	if (!isNotNull(beibao.食物)) {
		//判断老存档有没有食物字段
		beibao.食物 = [];
	}
    await Write_beibao(GROUP_ID, ID, beibao);
    let exist = await exist_beibao_thing(GROUP_ID, ID, name, thing_class);
    let cs_list = data.cs_list;
    if (thing_class === '饮料') {
        // 尝试找到饮料对象
        let drinkItem = beibao.饮料.find((item) => item.name === name);
        let wp= cs_list.find((item) => item.name === name);
        if (!drinkItem) {
            // 如果饮料不存在，并且x大于0，表示需要创建新饮料
            if (x > 0) {
                drinkItem = { name, 数量: x,class:wp.class,体力恢复:wp.体力恢复,精力恢复:wp.精力恢复,零售价:wp.零售价,desc:wp.desc};
                beibao.饮料.push(drinkItem);
                await Write_beibao(GROUP_ID, ID, beibao);
                return;
            } else {
                // 如果饮料不存在且x不大于0，则无需做任何操作
                return;
            }
        }

        // 如果饮料存在，则更新数量
        drinkItem.数量 += x;

        // 如果数量小于1，则从背包中移除该饮料
        if (drinkItem.数量 < 1) {
            beibao.饮料 = beibao.饮料.filter((item) => item.name !== name);
        }

        // 保存背包状态
        await Write_beibao(GROUP_ID, ID, beibao);
        return;
    }
    if (thing_class === '食物') {
        // 尝试找到食物对象
        let drinkItem = beibao.食物.find((item) => item.name === name);
        let wp= cs_list.find((item) => item.name === name);
        if (!drinkItem) {
            // 如果饮料不存在，并且x大于0，表示需要创建新食物
            if (x > 0) {
                drinkItem = { name, 数量: x,class:wp.class,体力恢复:wp.体力恢复,精力恢复:wp.精力恢复,零售价:wp.零售价,desc:wp.desc};
                beibao.食物.push(drinkItem);
                await Write_beibao(GROUP_ID, ID, beibao);
                return;
            } else {
                // 如果食物不存在且x不大于0，则无需做任何操作
                return;
            }
        }

        // 如果食物存在，则更新数量
        drinkItem.数量 += x;

        // 如果数量小于1，则从背包中移除该食物
        if (drinkItem.数量 < 1) {
            beibao.食物 = beibao.食物.filter((item) => item.name !== name);
        }

        // 保存背包状态
        await Write_beibao(GROUP_ID, ID, beibao);
        return;
    }

}
//读取背包
export async function Read_beibao(GROUP_ID, ID) {
	let dir = path.join(FILE_PATH['player'], GROUP_ID.toString(), 'beibao' ,ID + '.json');
	let beibao = fs.readFileSync(dir, 'utf8', (err, data) => {
		if (err) {
			console.log(err);
			return 'error';
		}
		return data;
	});
	//将字符串数据转变成数组格式
	beibao = JSON.parse(beibao);
	return beibao;
}
//读取工作内容
export async function Read_work(GROUP_ID, ID) {
	let dir = path.join(FILE_PATH['player'], GROUP_ID.toString(), 'work' ,ID + '.json');
	let work = fs.readFileSync(dir, 'utf8', (err, data) => {
		if (err) {
			console.log(err);
			return 'error';
		}
		return data;
	});
	//将字符串数据转变成数组格式
	work = JSON.parse(work);
	return work;
}
//写入背包
export async function Write_beibao(GROUP_ID, ID, beibao) {
	let dir = path.join(FILE_PATH['player'], GROUP_ID.toString(), 'beibao' ,ID + '.json');
	let new_ARR = JSON.stringify(beibao, '', '\t');
	fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
		console.log('写入成功', err);
	});
	return;
}
/**
 *
 * @param {*} GROUP_ID, ID 玩家qq
 * @param {*} thing_name 物品名
 * @param {*} thing_class 物品类别
 * @param {*} thing_pinji 可选参数，装备品阶，数字0-6等
 * @returns 物品数量或者false
 */
//检查背包内物品是否存在
//判断物品
//要用await
export async function exist_beibao_thing(GROUP_ID, ID,thing_name,thing_class,thing_pinji = null){
    let beibao = await Read_beibao(GROUP_ID, ID);
    if (!isNotNull(beibao.饮料)) {
		beibao.饮料 = [];
		await Write_beibao(GROUP_ID, ID, beibao);
	}
	if (!isNotNull(beibao.食物)) {
		beibao.食物 = [];
		await Write_beibao(GROUP_ID, ID, beibao);
	}
    let ifexist;
    if (thing_class == '饮料') {
		ifexist = beibao.饮料.find((item) => item.name == thing_name);
	}
    if (thing_class == '食物') {
		ifexist = beibao.食物.find((item) => item.name == thing_name);
	}
    if (ifexist) {
		return ifexist.数量;
	}
    return false;
}
export function isNotNull(obj) {
	if (obj == undefined || obj == null) return false;
	return true;
}
/**
 * 返回该玩家的背包图片
 * @return image
 */
export async function get_beibao_img(GID, ID,e) {
    let player = await getPlayerData(GID,ID);
    let beibao = await Read_beibao(GID,ID);
    const xingbi = Math.trunc(beibao.xingbi);
    let player_data = {
        user_id: ID,
        player: player,
        beibao: beibao,
        player_jingli: player.jingli,
        player_jtili: player.tili,
        beibao_xingbi: xingbi,
        beibao_shiwu: beibao.食物,
        beibao_yinliao: beibao.饮料
    }
    const data1 = await new Show(e).get_beibaoData(player_data);
    return await puppeteer.screenshot("beibao", {
        ...data1,
    });
}
/**
 * 返回该玩家的工作内容图片
 * @return image
 */
export async function get_work_img(GID, ID,e) {
    let player = await getPlayerData(GID,ID);
    let work = await Read_work(GID,ID);
    const date_time = new Date().getTime();//获取今天服务器时间
    let date_time2 = await redis.get(`Yunzai:xdxzgowork${ID}_time`);date_time2 = JSON.parse(date_time2); //获取用户上一次回宿舍时间
    let time = date_time-date_time2;
    // 创建一个新的 Date 对象
    const date = new Date(time);
    // 格式化时间
    const hours = ('0' + date.getHours()).slice(-2);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);
    const formattedTime = `${hours}:${minutes}:${seconds}`;
    let player_data = {
        user_id: ID,
        player: player,
        work: work,
        time: formattedTime
    }
    const data1 = await new Show(e).get_workData(player_data);
    return await puppeteer.screenshot("work", {
        ...data1,
    });
}
/**
 *
 * @param {*} thing_name 物品名
 * @returns
 */
//遍历物品
export async function foundthing(thing_name) {
    for (var i = 0; i < data.cs_list.length; i++) {
		if (thing_name == data.cs_list[i].name) {
			return data.cs_list[i];
		}
	}
    return false;
}